package com.vhall.component.service.room.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.base.Splitter;
import com.vhall.component.dao.record.RecordMapper;
import com.vhall.component.dao.room.AnchorRoomRelationMapper;
import com.vhall.component.dao.room.InvestRefRelationMapper;
import com.vhall.component.dao.room.RoomDraftRecordMapper;
import com.vhall.component.dao.room.TagOfRoomMapper;
import com.vhall.component.entity.inav.vo.SelectVideoData;
import com.vhall.component.entity.inav.vo.TagVO;
import com.vhall.component.entity.page.vo.PageVO;
import com.vhall.component.entity.rbac.enums.RoleTypeEnum;
import com.vhall.component.entity.record.RecordEntity;
import com.vhall.component.entity.room.dto.WhiteFileDTO;
import com.vhall.component.entity.room.entity.*;
import com.vhall.component.entity.room.enums.*;
import com.vhall.component.entity.room.vo.*;
import com.vhall.component.entity.tag.TagEntity;
import com.vhall.component.entity.thirduser.ThirdUserVO;
import com.vhall.component.framework.common.exception.BusinessException;
import com.vhall.component.framework.common.utils.CollectionUtils;
import com.vhall.component.plugin.common.exception.BizErrorCode;
import com.vhall.component.plugin.common.support.Token;
import com.vhall.component.plugin.common.support.TokenThreadLocal;
import com.vhall.component.service.common.BaseCommonService;
import com.vhall.component.service.room.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author xing.wang
 * @description 针对表【room_draft_record(直播草稿记录表)】的数据库操作Service实现
 * @createDate 2023-08-09 17:12:27
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class RoomDraftRecordServiceImpl extends ServiceImpl<RoomDraftRecordMapper, RoomDraftRecordEntity>
        implements RoomDraftRecordService {
    private final RoomDraftRecordMapper roomDraftRecordMapper;
    private final InvestRefRelationMapper investRefRelationMapper;

    private final AnchorRoomRelationService anchorRoomRelationService;
    private final AnchorRoomRelationMapper anchorRoomRelationMapper;
    private final InvestRefRelationService investRefRelationService;
    private final InvestRefService investRefService;
    private final RecordMapper recordMapper;
    private final TagOfRoomMapper tagOfRoomMapper;
    private final BaseCommonService baseCommonService;
    private final RoomProdRelationService roomProdRelationService;
    private final RoomWhiteFileRelationService whiteFileRelationService;
    private final RoomWhitePhoneRelationService whitePhoneRelationService;
    private final RoomCacheLockService roomCacheLockService;

    @Override
    public Boolean saveRoomDraft(SaveRoomDraftRequestVO vo) {
        Token token = TokenThreadLocal.getToken();
        Integer roomDraftId = vo.getRoomDraftId();
        RoomDraftRecordEntity roomDraftRecordEntity = getRoomDraftRecordEntity(roomDraftId);
        roomDraftRecordEntity.setUpdatedAt(LocalDateTime.now());
        roomDraftRecordEntity.setUpdateBy(token.getAccountId());
        roomDraftRecordEntity.setOrgCode(token.getOrgCode());
        roomDraftRecordEntity.setOrgName(token.getOrgName());
        BeanUtil.copyProperties(vo, roomDraftRecordEntity);
        roomDraftRecordEntity.setValid(ValidEnum.VALID.getValue());
        buildGuoXinRoomInfo(roomDraftRecordEntity, vo);
        roomDraftRecordEntity.setCoverImage(vo.getImageUrl());
        int i = roomDraftRecordMapper.updateById(roomDraftRecordEntity);
        boolean result = i >= 1;
        if (result) {
            handleSaveRoomDraftAfter(vo, token, roomDraftId);
        }
        return result;
    }

    /**
     * 构建国信项目新增的房间信息
     *
     * @param room
     * @param reqVO
     * @return
     */
    private RoomDraftRecordEntity buildGuoXinRoomInfo(RoomDraftRecordEntity room, SaveRoomDraftRequestVO reqVO) {
        room.setSubject(reqVO.getName());

        LocalDateTime begin = LocalDateTime.now();
        if (StringUtils.isNotBlank(reqVO.getBeginTime())) {
            begin = LocalDateTimeUtil.parse(reqVO.getBeginTime(), DatePattern.NORM_DATETIME_PATTERN);
        }
        room.setStartTime(begin);
        room.setColumnId(reqVO.getColumnId());
        room.setLiveContentType(reqVO.getLiveContentType());
        String accountVerification = StrUtil.isBlank(reqVO.getAccountVerification()) ? "0" : reqVO.getAccountVerification();
        room.setAccountVerification(accountVerification);
        room.setRiskLive(reqVO.getRiskLive());
        room.setInvestLimit(reqVO.getInvestLimit());
        room.setInvestType(reqVO.getInvestType());
        room.setPermissions(reqVO.getPermissions());
        room.setLiveBusiness(reqVO.getLiveBusiness());
        room.setLiveTarget(reqVO.getLiveTarget());
        room.setReviewOaId(reqVO.getReviewOaId());
        room.setReviewOaName(reqVO.getReviewOaName());
        room.setReviewOaUrl(reqVO.getReviewOaUrl());
        room.setLiveRormal(reqVO.getLiveRormal());
        room.setWelcomMessage(reqVO.getWelcomMessage());

        Integer warmType = reqVO.getWarmType();
        room.setWarmType(warmType);
        if (Objects.equals(RoomsWarmTypeEnum.VIDEO.getValue(),warmType)) {
            if (StrUtil.isNotBlank(reqVO.getWarmVodId())) {
                room.setWarmVodId(reqVO.getWarmVodId());
            }
        }
        room.setLiveInlet(reqVO.getLiveInlet());

        if (Objects.equals(LivePaidStatusEnum.PAID_LIVE.getValue(),reqVO.getIsPaid())) {
            room.setIsPaid(LivePaidStatusEnum.PAID_LIVE.getValue());
            String paidProductCode = reqVO.getPaidProductCode();
            room.setPaidProductCode(paidProductCode);
            room.setPaidPrice("");
            room.setOriginalPrice("");
        }else{
            room.setIsPaid(LivePaidStatusEnum.FREE_LIVE.getValue());
            room.setPaidProductCode("");
        }

        Integer limitUserScope = reqVO.getLimitUserScope();
        if (Objects.nonNull(limitUserScope)) {
            room.setLimitUserScope(limitUserScope);
        }else{
            room.setLimitUserScope(LiveLimitUserScopeEnum.ALL_USER_VISIBLE.getValue());
        }
        return room;
    }

    private void handleSaveRoomDraftAfter(SaveRoomDraftRequestVO vo, Token token, Integer roomDraftId) {
        List<ThirdUserVO> anchorInfoList = vo.getAnchorInfoList();
        if (CollUtil.isNotEmpty(anchorInfoList)) {
            Integer accountId = token.getAccountId();
            anchorRoomRelationService.relationRoomDraftToThirdUser(accountId, roomDraftId, anchorInfoList);
        } else {
            LambdaQueryWrapper<AnchorRoomRelationEntity> queryWrapper = Wrappers.lambdaQuery();
            queryWrapper.eq(AnchorRoomRelationEntity::getRoomDraftRecordId, roomDraftId);
            anchorRoomRelationService.remove(queryWrapper);
        }
        List<InvestRefVO> investRefList = vo.getInvestRefList();
        relationRoomDraftToInvestRef(investRefList, roomDraftId);
        relationRoomDraftToGuoxinProd(vo,roomDraftId);
        relationWhitePhoneFileToRoom(vo,roomDraftId);
    }

    private void relationRoomDraftToGuoxinProd(SaveRoomDraftRequestVO reqVO, Integer roomDraftId) {
        Integer roomDraftRecordId = roomDraftId;
        List<String> exemptProdCodes = reqVO.getExemptProdCodes();
        roomProdRelationService.relationRoomToGuoxinProd(exemptProdCodes, roomDraftRecordId, "", 0, RoomAssociationTypeEnum.EXEMPTION_ASSOCIATION.getValue());
        if (Objects.equals(LiveLimitUserScopeEnum.HOLDING_PRODUCT_USER_VISIBLE.getValue(),reqVO.getLimitUserScope())) {
            List<String> visibleProdCodes = reqVO.getVisibleProdCodes();
            roomProdRelationService.relationRoomToGuoxinProd(visibleProdCodes, roomDraftRecordId, "", 0, RoomAssociationTypeEnum.PURCHASE_ASSOCIATION.getValue());
        }
    }
    /**
     * 关联房间和白名单手机号和白名单文件
     * @param reqVO
     * @param roomDraftId
     */
    private void relationWhitePhoneFileToRoom(SaveRoomDraftRequestVO reqVO, Integer roomDraftId) {
        if (Objects.equals(reqVO.getLimitUserScope(), LiveLimitUserScopeEnum.WHITELIST_USER_VISIBLE.getValue())) {
            Integer whiteFileId = reqVO.getWhiteFileId();
            clearRoomRelationWhiteInfo(whiteFileId, roomDraftId);
            RoomWhiteFileRelationEntity whiteFileRelationEntity = whiteFileRelationService.getById(whiteFileId);
            if (Objects.nonNull(whiteFileRelationEntity)) {
                whiteFileRelationEntity.setRoomDraftRecordId(roomDraftId);
                whiteFileRelationService.updateById(whiteFileRelationEntity);
                whitePhoneRelationService.batchChangeRoomWhitePhoneRelationInfo(whiteFileId, 0, roomDraftId);
            }
        }
    }
    /**
     * 清理房间与白名单文件和白名单手机号的关联
     * @param whiteFileId 白名单文件 id
     * @param roomDraftId 草稿id
     */
    private void clearRoomRelationWhiteInfo(Integer whiteFileId, Integer roomDraftId) {
        LambdaQueryWrapper<RoomWhiteFileRelationEntity> fileRelationEntityLambdaQueryWrapper = Wrappers.lambdaQuery();
        fileRelationEntityLambdaQueryWrapper.eq(RoomWhiteFileRelationEntity::getRoomDraftRecordId, roomDraftId).last(" limit 1");
        RoomWhiteFileRelationEntity oldWhiteFile = whiteFileRelationService.getOne(fileRelationEntityLambdaQueryWrapper);
        if (Objects.nonNull(oldWhiteFile)) {
            if (!Objects.equals(whiteFileId,oldWhiteFile.getId())) {
                oldWhiteFile.setIlId(0);
                oldWhiteFile.setRoomDraftRecordId(0);
                whiteFileRelationService.updateById(oldWhiteFile);
                whitePhoneRelationService.batchChangeRoomWhitePhoneRelationInfo(whiteFileId, 0, 0);
            }
        }
    }
    /**
     * 关联房间草稿和投资依据
     *
     * @param investRefList
     * @param roomDraftId
     */
    private void relationRoomDraftToInvestRef(List<InvestRefVO> investRefList, Integer roomDraftId) {

        if (CollUtil.isNotEmpty(investRefList)) {
            LambdaQueryWrapper<InvestRefEntity> investRefWhere = Wrappers.lambdaQuery();
            List<Integer> investRefIds = investRefList.stream().map(InvestRefVO::getInvestRefId).collect(Collectors.toList());
            investRefWhere.in(InvestRefEntity::getId, investRefIds);
            List<InvestRefEntity> investRefEntities = investRefService.list(investRefWhere);
            if (CollUtil.isNotEmpty(investRefEntities)) {
                AddInvestRefRelationVO dto = new AddInvestRefRelationVO();
                dto.setRoomDraftRecordId(roomDraftId);
                dto.setInvestRefIds(investRefIds);
                investRefRelationService.addInvestRefRelation(dto);
            }
        } else {
            LambdaQueryWrapper<InvestRefRelationEntity> deleteWhere = Wrappers.lambdaQuery();
            deleteWhere.eq(InvestRefRelationEntity::getRoomDraftRecordId, roomDraftId);
            investRefRelationService.remove(deleteWhere);
        }
    }

    @Override
    public Boolean deleteRoomDraft(DeleteRoomDraftRequestVO vo) {
        Integer roomDraftId = vo.getRoomDraftId();
        RoomDraftRecordEntity roomDraftRecordEntity = getRoomDraftRecordEntity(roomDraftId);
        roomDraftRecordEntity.setDeletedAt(LocalDateTime.now());
        int i = roomDraftRecordMapper.updateById(roomDraftRecordEntity);
        return i >= 1;
    }

    @Override
    public PageVO<RoomDraftListResponseVO> pageList(RoomDraftPageListRequestVO vo) {
        String keyword = vo.getKeyword();
        LambdaQueryWrapper<RoomDraftRecordEntity> where = Wrappers.lambdaQuery();
        String userPermission = getUserPermission();
        where.isNull(RoomDraftRecordEntity::getDeletedAt)
                .eq(StringUtils.isNotBlank(userPermission), RoomDraftRecordEntity::getOrgCode, userPermission)
                .eq(RoomDraftRecordEntity::getValid, ValidEnum.VALID.getValue())
                .and(StrUtil.isNotBlank(keyword), w -> w.eq(RoomDraftRecordEntity::getId, keyword)
                        .or()
                        .like(RoomDraftRecordEntity::getSubject, keyword)
                        .or()
                        .apply(" EXISTS(select anchor_room_relation.id from anchor_room_relation where anchor_room_relation.room_draft_record_id=room_draft_record.id " +
                                " and anchor_room_relation.user_name like CONCAT('%',{0},'%') )",keyword))
                .orderByDesc(RoomDraftRecordEntity::getId);
        Integer pageIndex = vo.getPage();
        Integer pageSize = vo.getPageSize();
        Page<RoomDraftRecordEntity> page = new Page<>(pageIndex, pageSize);
        Page<RoomDraftRecordEntity> pageOrgData = roomDraftRecordMapper.selectPage(page, where);
        List<RoomDraftListResponseVO> list = new ArrayList<>();
        if (Objects.nonNull(pageOrgData) && pageOrgData.getTotal() > 0) {
            List<RoomDraftRecordEntity> records = pageOrgData.getRecords();
            // 投资依据信息
            Map<Integer, List<InvestRefEntity>> investMap = getRoomDraftInvestInfo(records);
            // 获取主播名称
            Map<Integer, String> userNameMap = getUserName(records);
            list = records.stream().map(entity -> {
                RoomDraftListResponseVO tempData = new RoomDraftListResponseVO();
                BeanUtil.copyProperties(entity, tempData, false);
                if (CollUtil.isNotEmpty(investMap)) {
                    tempData.setInvestRefListFlag(investMap.containsKey(entity.getId()));
                } else {
                    tempData.setInvestRefListFlag(false);
                }
                tempData.setLiveContentTypeName(LiveContentTypeEnum.getDescription(tempData.getLiveContentType()));
                if (CollUtil.isNotEmpty(userNameMap)) {
                    tempData.setUserName(userNameMap.get(entity.getId()));
                } else {
                    tempData.setUserName("");
                }
                baseCommonService.convertUrl(tempData, "coverImage");
                return tempData;
            }).collect(Collectors.toList());
        }
        return new PageVO<>(pageIndex, pageSize, (int) page.getTotal(), list);
    }

    /**
     * 通过草稿信息查找草稿对应的主播名称
     *
     * @param records
     * @return
     */
    private Map<Integer, String> getUserName(List<RoomDraftRecordEntity> records) {
        List<AnchorRoomRelationEntity> relationEntities = anchorRoomRelationMapper.selectInfoDraftList(records.stream().map(RoomDraftRecordEntity::getId).collect(Collectors.toList()));
        Map<Integer, String> stringMap = new HashMap<>();
        if (CollectionUtils.isNotEmpty(relationEntities)) {
            stringMap = relationEntities.stream().collect(Collectors.toMap(AnchorRoomRelationEntity::getRoomDraftRecordId, AnchorRoomRelationEntity::getUserName));
        }
        return stringMap;
    }

    private Map<Integer, List<InvestRefEntity>> getRoomDraftInvestInfo(List<RoomDraftRecordEntity> records) {
        List<Integer> roomDraftRecordIds = records.stream().map(RoomDraftRecordEntity::getId).collect(Collectors.toList());

        List<InvestRefEntity> entities = investRefRelationMapper.selectDetailDraftList(roomDraftRecordIds);

        Map<Integer, List<InvestRefEntity>> result = new HashMap<>();
        if (CollectionUtils.isNotEmpty(entities)) {
            LambdaQueryWrapper<InvestRefRelationEntity> where2 = Wrappers.lambdaQuery();
            where2.in(InvestRefRelationEntity::getRoomDraftRecordId, roomDraftRecordIds);
            List<InvestRefRelationEntity> entityList = investRefRelationMapper.selectList(where2);

            Map<Integer, List<InvestRefRelationEntity>> listMap = entityList.stream().collect(Collectors.groupingBy(InvestRefRelationEntity::getRoomDraftRecordId));
            Map<Integer, InvestRefEntity> investRefEntityMap = entities.stream().collect(Collectors.toMap(InvestRefEntity::getId, e -> e,(e1,e2)->e1));

            for (Map.Entry<Integer, List<InvestRefRelationEntity>> listEntry : listMap.entrySet()) {
                Integer roomDraftRecordId = listEntry.getKey();
                List<InvestRefRelationEntity> listEntryValue = listEntry.getValue();
                List<InvestRefEntity> list = new ArrayList<>();
                for (InvestRefRelationEntity investRefRelationEntity : listEntryValue) {

                    list.add(investRefEntityMap.get(investRefRelationEntity.getInvestRefId()));
                }

                result.put(roomDraftRecordId, list);
            }
        }
        return result;
    }

    @Override
    public GetRoomDraftResponseVO getRoomDraftInfo(GetRoomDraftRequestVO vo) {
        Integer roomDraftId = vo.getRoomDraftId();
        GetRoomDraftResponseVO result = new GetRoomDraftResponseVO();
        if (roomDraftId != 0) {
            buildRoomDraftInfo(roomDraftId, result);
        } else {
            Token token = TokenThreadLocal.getToken();
            RoomDraftRecordEntity entity = new RoomDraftRecordEntity();
            entity.setValid(ValidEnum.INVALID.getValue());
            entity.setUpdateBy(token.getAccountId());
            LocalDateTime now = LocalDateTime.now();
            entity.setUpdatedAt(now);
            entity.setCreatedAt(now);
            entity.setAccountId(token.getAccountId());
            roomDraftRecordMapper.insert(entity);
            Integer id = entity.getId();
            result.setId(id);
            Map<String, Object> warmInfo = getRoomDraftWarmInfo(entity);
            result.setWarmInfo(warmInfo);
        }
        return result;
    }

    private void buildRoomDraftInfo(Integer roomDraftId, GetRoomDraftResponseVO result) {
        RoomDraftRecordEntity roomDraftRecordEntity = getRoomDraftRecordEntity(roomDraftId);
        BeanUtil.copyProperties(roomDraftRecordEntity, result, "topics");
        result.setBeginTime(roomDraftRecordEntity.getStartTime());
        result.setAnchorInfoList(getAnchorRoomInfo(roomDraftId));
        RoomInvestRefRelationListRequestVO roomInvestRefRelationListRequestVO = new RoomInvestRefRelationListRequestVO();
        roomInvestRefRelationListRequestVO.setRoomDraftRecordId(roomDraftId);
        String vodId = roomDraftRecordEntity.getDemandVodId();
        if (StringUtils.isNotBlank(vodId)) {
            LambdaQueryWrapper<RecordEntity> where = Wrappers.lambdaQuery();
            where.eq(RecordEntity::getVodId, vodId);
            List<RecordEntity> recordEntities = recordMapper.selectList(where);
            if (CollectionUtils.isNotEmpty(recordEntities)) {
                result.setSelectVideoData(SelectVideoData.builder().demandVodId(vodId).name(recordEntities.get(0).getName()).build());
            }
        }
        // 对topic做特殊处理
        List<TagVO> tags = new ArrayList<>();
        if (StringUtils.isNotBlank(roomDraftRecordEntity.getTopics())) {
            List<String> tagList = Splitter.on(",").splitToList(roomDraftRecordEntity.getTopics());
            LambdaQueryWrapper<TagEntity> wrapper = Wrappers.lambdaQuery();
            wrapper.in(TagEntity::getTagId, tagList);
            List<TagEntity> tagEntities = tagOfRoomMapper.selectList(wrapper);
            if (CollectionUtils.isNotEmpty(tagEntities)) {
                TagVO tagVO;
                for (TagEntity single : tagEntities) {
                    tagVO = new TagVO();
                    tagVO.setName(single.getName());
                    tagVO.setTagId(single.getTagId());
                    tags.add(tagVO);
                }
            }
        }
        result.setTopics(tags);
        result.setInvestRefList(investRefService.getRoomInvestRefRelationList(roomInvestRefRelationListRequestVO));
        //        适当性豁免产品的编号产品编号列表
        result.setExemptProdCodes(getRoomExemptProdCodes(roomDraftId));
//        仅限持仓产品的客户可见产品编号列表
        result.setVisibleProdCodes(getRoomVisibleProdCodes(roomDraftId));
//        白名单文件信息
        WhiteFileDTO roomWhiteFileInfo = getRoomWhiteFileInfo(roomDraftId);
        result.setWhiteFileInfo(roomWhiteFileInfo);
        result.setWhiteFileId(roomWhiteFileInfo.getId());
        Map<String, Object> warmInfo = getRoomDraftWarmInfo(roomDraftRecordEntity);
        result.setWarmInfo(warmInfo);
    }

    @NotNull
    private Map<String, Object> getRoomDraftWarmInfo(RoomDraftRecordEntity roomDraftRecordEntity) {
        Map<String, Object> warmInfo = new HashMap<>(8);
        // 默认暖场为图片
        Integer warmType = Optional.ofNullable(roomDraftRecordEntity.getWarmType()).orElse(0);
        warmInfo.put("type", warmType);
        if (Objects.equals(warmType,1)) {
            String warmVodId = roomDraftRecordEntity.getWarmVodId();
            RecordEntity recordEntity = roomCacheLockService.getCachedWarmRecordInfo(warmVodId);
            if (Objects.nonNull(recordEntity)) {
                warmInfo.put("vod_name", recordEntity.getName());
            }else{
                warmInfo.put("vod_name", "");
            }
            warmInfo.put("vod_id", warmVodId);
            warmInfo.put("img", "");
        }
        return warmInfo;
    }

    /**
     * 获取房间草稿关联的白名单文件信息
     * @param roomDraftId
     * @return
     */
    private WhiteFileDTO getRoomWhiteFileInfo(Integer roomDraftId) {
        LambdaQueryWrapper<RoomWhiteFileRelationEntity> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(RoomWhiteFileRelationEntity:: getRoomDraftRecordId,roomDraftId).last("limit 1");
        RoomWhiteFileRelationEntity one = whiteFileRelationService.getOne(queryWrapper);
        WhiteFileDTO result = new WhiteFileDTO();
        if (Objects.nonNull(one)) {
            result.setId(one.getId());
            result.setFileName(one.getFileName());
            result.setFileUrl(one.getFileUrl());
        }
        return result;
    }
    /**
     * 获取草稿适当性豁免关联的产品编码
     * @param roomDraftId
     * @return
     */
    private List<String> getRoomExemptProdCodes(Integer roomDraftId) {
        return getDraftProdRelationOfCodes(roomDraftId,RoomAssociationTypeEnum.EXEMPTION_ASSOCIATION.getValue());
    }
    /**
     * 获取草稿关联的观看范围限定购买产品的产品编码
     * @param roomDraftId
     * @return
     */
    private List<String> getRoomVisibleProdCodes(Integer roomDraftId) {
        return getDraftProdRelationOfCodes(roomDraftId,RoomAssociationTypeEnum.PURCHASE_ASSOCIATION.getValue());
    }
    /**
     *
     * @param roomDraftId
     * @param purchaseAssociationValue 关联房间类型| 0：适当性豁免关联产品 1：观看范围限定购买产品
     * @return
     */
    @NotNull
    private List<String> getDraftProdRelationOfCodes(Integer roomDraftId, Integer purchaseAssociationValue) {
        LambdaQueryWrapper<RoomProdRelationEntity> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(RoomProdRelationEntity::getRoomDraftRecordId, roomDraftId).eq(RoomProdRelationEntity::getType, purchaseAssociationValue);
        List<RoomProdRelationEntity> list = roomProdRelationService.list(queryWrapper);
        return list.stream().map(RoomProdRelationEntity::getOfcode).distinct().collect(Collectors.toList());
    }
    @Override
    public List<InvestRefResponseVO> getRoomDraftInvestRefList(RoomInvestRefRelationListRequestVO vo) {
        return investRefService.getRoomInvestRefRelationList(vo);
    }

    private RoomDraftRecordEntity getRoomDraftRecordEntity(Integer roomDraftId) {
        LambdaQueryWrapper<RoomDraftRecordEntity> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(RoomDraftRecordEntity::getId, roomDraftId).last(" limit 1");
        return Optional.ofNullable(roomDraftRecordMapper.selectOne(queryWrapper))
                .orElseThrow(() -> new BusinessException(BizErrorCode.EMPTY_ROOM_DRAFT));
    }

    /**
     * 获取房间草稿与主播关联信息
     *
     * @param roomDraftId 草稿 ID
     * @return 房间与主播关联信息
     */
    private List<ThirdUserVO> getAnchorRoomInfo(Integer roomDraftId) {
        List<ThirdUserVO> result;
        LambdaQueryWrapper<AnchorRoomRelationEntity> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(AnchorRoomRelationEntity::getRoomDraftRecordId, roomDraftId);
        List<AnchorRoomRelationEntity> list = anchorRoomRelationService.list(queryWrapper);
        result = Optional.ofNullable(list.stream().map(data -> {
            ThirdUserVO temp = new ThirdUserVO();
            temp.setName(data.getUserName());
            temp.setUserCode(data.getUserCode());
            temp.setUserType(data.getUserType());
            temp.setOrgName(data.getOrgName());
            temp.setOrgCode(data.getOrgCode());
            temp.setAdvisorLicenseNo(data.getAdvisorLicenseNo());
            return temp;
        }).collect(Collectors.toList())).orElse(new ArrayList<>());
        return result;
    }

    /**
     * 获取当前人员查看权限
     * 部门级别人员，返回指定部门；
     * 平台级人员，返回空
     */
    public String getUserPermission() {

        Token token = TokenThreadLocal.getToken();
        if (RoleTypeEnum.DEPT_LEVEL.getValue().equals(token.getRoleType())) {
            return token.getOrgCode();
        }

        return null;

    }
}




